package com.yhy.common.rabbitmq.callback;

import cn.hutool.json.JSONUtil;
import com.yhy.common.rabbitmq.config.DefaultDelayConfig;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * 消息到达交换机，没有路由到队列
 */
@Slf4j
public abstract class ReturnsCallback implements RabbitTemplate.ReturnsCallback {

    @Override
    public void returnedMessage(@NonNull ReturnedMessage returned) {
        /*
         * 1 交换机没有绑定队列
         * 2 交换机根据路由键没有匹配到队列
         * 3 队列消息已满
         */
        MessageProperties messageProperties = returned.getMessage().getMessageProperties();
        if (DefaultDelayConfig.X_DELAYED_MESSAGE.equals(messageProperties.getType()) && returned.getReplyCode() == 312) {
            log.warn("延迟队列插件发送消息...补偿忽略");
            return;
        }
        log.error("failed to published message to queue!");
        log.error("messageId : {}", messageProperties.getMessageId());
        log.error("message   : {}", JSONUtil.toJsonStr(new String(returned.getMessage().getBody())));
        log.error("replyCode : {}", returned.getReplyCode());
        log.error("replyText : {}", returned.getReplyText());
        log.error("exchange  : {}", returned.getExchange());
        log.error("routingKey: {}", returned.getRoutingKey());
        compensate(returned);
    }

    protected abstract void compensate(ReturnedMessage returned);


}
